<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/20 0020
 * Time: 下午 8:28
 */

namespace app\admin\controller;


use app\admin\model\ArticleModel;
use app\admin\model\MusicModel;
use app\admin\model\UserModel;
use app\admin\validate\ArticleValidate;
use think\facade\Cookie;
use think\Image;
use think\Paginator;
use think\Request;

class Article extends Base
{
    protected $size = 2 * 1024 * 1024;
    protected $ext = 'jpg,png,gif,bmp';
    protected $avatarPath = "../../../reader/images/avatar"; //头像储存位置
    protected $articlePath = "../../../reader/images/post";  //新闻图片储存位置

    /**
     * 新闻文章渲染
     * @return mixed
     */

    public function index()
    {
        $userId = Cookie::get("userId");
        $result = (new UserModel())->get($userId)->role()->field("id")->find();
        if (!in_array($result["id"],["1","2"]) ) {
            $this->assign("error",false);
        }
        return $this->fetch();
    }


    /**
     * 获取所有文章
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getArticleAll(Request $request)
    {
        if ($request->isAjax()) {
            $limit = $request->param("limit");
            $model = new ArticleModel();
            $result  = $model->order("create_time","DESC")
                ->paginate($limit);

            foreach ($result as $key => $value) {
                $result[$key]["author"] = $value["user"]["username"];
            }
            //$this->assign("data",$result);

            return json(["code" => 0, "msg" => "ok","count" => $result->total() ,"data" => $result->items()]);
        }
    }

    /**
     * 增加页面渲染
     * @return mixed
     */
    public function add()
    {
        $user_id = Cookie::get("userId");
        $author = UserModel::get($user_id);
        $this->assign("user",["id" => $author["id"],"author" => $author["username"]]);
        $this->assign("imageUrl",$this->imageUrl);
        $this->assign("data",$this->getMusic());
        return $this->fetch();
    }

    /**
     * 获取音乐 遍历下拉框
     * @return array
     */
    protected function getMusic()
    {
        $data = MusicModel::getMusicAll();
        if (empty($data)) {
            $data = [];
        }
        return $data;
    }

    /**
     * 添加新闻
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\PDOException
     */
    public function addArticle(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();

            $validate = new ArticleValidate();
            if (!$validate->check($data)) {
                return json(["code" => 403,"msg" => "验证失败" ,"data" => $validate->getError(),"token" => $request->token()]);
            }
            $result = ArticleModel::addArticle($data);

            if ($result !== true) {
                return json(["code" => 403,"msg" => "数据上传失败" ,"data" => $result,"token" => $request->token()]);
            }
            return json(["code" => 1,"msg" => "添加成功"]);
        }
    }

    /**
     * 文章修改
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        if ($request->isGet()) {
            $id = $request->param("id");
            $result = ArticleModel::getArticleFind($id);
            $result["author"] = $result["user"]["username"];
            $result["detail"] = $result["articleInfo"]["detail"];
            $this->assign("music",$this->getMusic());
            $this->assign("article",$result);
            $this->assign("imageUrl",$this->imageUrl);
            return  $this->fetch();
        }
    }


    /**
     * 修改文章
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\PDOException
     */
    public function editArticle(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $validate = new ArticleValidate();
            if (!$validate->check($data)) {
                return json(["code" => 403,"msg" => "验证失败" ,"data" => $validate->getError(),"token" => $request->token()]);
            }
            $data["update_time"] = time();
            $result = ArticleModel::editArticle($data);

            if ($result !== true) {
                return json(["code" =>403,"msg" => "数据修改失败" ,"data" => $result,"token" => $request->token()]);
            }
            return json(["code" => 1,"msg" => "修改","data" => "修改成功"]);
        }
    }

    /**
     * 删除新闻文章
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->param("id");

            $result = ArticleModel::delArticle($id);

            if ($result !== true) {
                return json(["code" => 403, "msg" => "删除", "data" => $result]);
            }

            return json(["code" => 1, "msg" => "删除", "data" => "删除成功"]);
        }
    }


    /**
     * 修改状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateStatus(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->param("id");
            $status = $request->param("status");

            $result = ArticleModel::updateStatus($id,$status);

            if ($result !== true) {
                return json(["code" => 403,"msg" => $status == 1 ? "禁用失败" : "启用失败"]);
            }
            return json(["code" => 1,"msg" => "更改成功"]);
        }
    }

    /**
     * 上传 头像
     * @param Request $request
     * @return \think\response\Json
     */
    public function uploadAvatarImage(Request $request)
    {
        $file = $request->file('file');

        $info = $file->validate(['size'=>$this->size,'ext'=>$this->ext])->move( $this->avatarPath);

        $imageName = $this->saveImage($info,$file);

        return json(["code" => 1, "msg" => "ok", "data" => $this->dealImageUrl($imageName)]);
    }

    /**
     * 处理图片地址
     * @param $imageName
     * @return bool|mixed|string
     */
    protected function dealImageUrl($imageName)
    {
        $length = stripos($imageName,"i");
        $imageName = substr($imageName,$length-1);
        $imageName = str_replace('\\','/',$imageName);
        return $imageName;
    }

    /**
     * 保存获取 文件地址
     * @param $info
     * @param $file
     * @return \think\response\Json
     */
    protected function saveImage($info,$file)
    {
        if ($info) {
            $imageName = $info->getPathname();

            $image = Image::open($imageName);

            $image->save($imageName);
        } else {
            return json(["code" => 403, "msg" => "文件上传失败","data" => $file->getError(),"token" => \think\facade\Request::token()]);
        }
        return $imageName;
    }

    /**
     * 上传 新闻图片
     * @param Request $request
     * @return \think\response\Json
     */
    public function uploadArticleImage (Request $request)
    {
        $file = $request->file('file');

        $info = $file->validate(['size'=>$this->size,'ext'=>$this->ext])->move( $this->articlePath);

        $imageName = $this->saveImage($info,$file);

        return json(["code" => 1, "msg" => "ok", "data" => $this->dealImageUrl($imageName)]);
    }

}